import {
  wxRequest
} from '../../../utils/server.js';
const _wxRequest = new wxRequest();
let util = require('../../../utils/util.js');
let moment = require('../../../utils/moment.js');
const app = getApp()
Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    startTime: '08:30',
    endTime: '21:00',
    coverImgsnum: wx.getStorageSync('picLimit')['sto_cover_num'] || 6,
    contentImgsnum: wx.getStorageSync('picLimit')['sto_content_num'] || 20,
    agentItem: {},
    staffItem: {},
    isEdit: false,
    canEdit: false,
    address: '',
    canUseLocation: false,
    id: '',
    isHide: false,
    cententDetail: {},
    coverVideo: '', // '/org/StoreVO/2019/11/19/VAX0EIQuSjGCIt4NCEOQzw.mp4',
    uploadUrl: wx.getStorageSync('uploadUrl'),
    hideSup: true,
    hideOpen: false,
    loading: false,
    isIphoneX: app.globalData.isIphoneX,
    coverImgs: [],
    extraNodes: [{
      type: "after",
      dragId: "plus",
      slot: "plus",
      fixed: true
    }],
    pageMetaScrollTop: 0,
    scrollTop: 0,
    contentImgs: [], //介绍图
    chainItem: {}
  },


  onLoad: function (options) {
    if (options && options.id) {
      this.setData({
        id: options.id
      })
      this.getdetail()
      this.getImg()
    } else {
      //发布代理商
      this.findAgentList()
    }

    // this.coverImgs = this.selectComponent("#coverImgs");
    // this.contentImgs = this.selectComponent("#contentImgs");

    this.dragcoverImgs = this.selectComponent('#dragcoverImgs');
    this.dragcoverImgs.init();
    //介绍图
    this.dragcontentImgs = this.selectComponent('#dragcontentImgs');
    this.dragcontentImgs.init();

    this.coverVideo = this.selectComponent("#coverVideo");
    this.contentVideo = this.selectComponent("#contentVideo")

    this.getChainList()
  },

  onShow: function () {
    this.checkLocationAuth()
    if (this.data.isEdit) {
      this.data.staffItem = []
      this.setData({
        staffItem: this.data.staffItem
      })
    }
    //不是平台隐藏选择供应商 
    if (wx.getStorageSync('userInfo').orgType == 1) {
      this.setData({
        hideSup: true,
        hideOpen: true
      })
    }
    // 不是平台和供货商管理隐藏开店人
    if (wx.getStorageSync('userInfo').orgType == 2) {
      this.setData({
        hideOpen: true
      })
    }
  },

  handleChain: function () {
    wx.navigateTo({
      url: '/pages/publish/template/chain?orgType=6',
    })
  },

  // 获取列表
  getChainList: function () {
    var that = this
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/org/protected/bizOrg/findChainList',
      method: 'POST',
      data: {
        orgType: 6
      }
    }, (res) => {
      var list = res.list
      console.log(res, 1111111);
      if (list.length == 1) {
        that.setData({
          // chainItem: {
          //   id: list[0].id,
          //   chqName: list[0].chqName
          // }
        })
      }

    })
  },

  clearChainItem () {
    this.setData({
      chainItem: []
    })
  },

  clearStaffItem () {
    this.setData({
      staffItem: []
    })
  },


  //选择商品图片
  chooseGoodsImg: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs,
      isHide: true
    })
  },

  deleteGoodsImg: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs
    })
  },

  deloriginGoodsImg: function () {
    this.setData({
      originImgs: this.details.data.originImgs
    })
  },

  completefun: function () {
    console.log('wanc')
    this.setData({
      isHide: false
    })
  },

  //选择介绍图片
  choosecontentImgs: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs
    })
  },

  deletecontentImgs: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs
    })
  },

  delorigincontentImgs: function () {
    this.setData({
      originImgs: this.details.data.originImgs
    })
  },

  //选择开始时间
  bindStartTimeChange: function (e) {
    this.setData({
      startTime: e.detail.value
    })
  },


  //选择结束时间
  bindEndTimeChange: function (e) {
    this.setData({
      endTime: e.detail.value
    })
  },



  //封面视频回调
  coverVideoCallback: function () {
    this.setData({
      coverVideo: this.coverVideo.data.video,
      coverVideoTime: '00:' + this.coverVideo.data.duration
    })
  },

  //介绍视频回调
  contentVideoCallback: function () {
    this.setData({
      contentVideo: this.contentVideo.data.video,
      contentVideoTime: '00:' + this.contentVideo.data.duration
    })
  },


  //监听地址详情
  addressDetail: function (e) {
    this.setData({
      address: e.detail
    })
  },


  //检查用户是否授权
  checkLocationAuth() {
    const self = this
    //获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userLocation']) {
          self.setData({
            canUseLocation: true,
          })
        } else {
          console.log("用户授权")
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              self.setData({
                canUseLocation: true,
              })
            },
            fail() {
              wx.showToast({
                icon: "none",
                title: '请允许获取字母歌小程序您的地理位置',
              })
            }
          })
        }
      }
    })
  },


  //选择详情地址
  chooseAddress() {
    const self = this
    if (!this.data.canUseLocation) {
      this.checkLocationAuth()
    }
    wx.chooseLocation({
      success: function (re) {
        console.log(re)
        self.setData({
          detailAddress: re.address,
          newAddressAlias: util.address2City(re.address),
          latitude: re.latitude,
          longitude: re.longitude,
        })
      },
      fail: function (re) {
        var msg = re.errMsg
        var reg = /auth deny/
        if (reg.test(msg)) {
          console.log("权限不足需要提示用户授权")
        }
      },
    })
  },



  goback: function () {
    wx.navigateBack({

    })
  },


  //选择代理商
  handleAgent: function () {
    wx.navigateTo({
      url: '/pages/publish/template/agent?isEdit=' + 0,
    })
  },

  handleStaff: function () {

    console.log(this.data.agentItem, 2222);
    wx.navigateTo({
      url: '/pages/publish/template/staff?isEdit=0&orgName=' + this.data.agentItem.ageName + '&orgId=' + this.data.agentItem.id + '&orgType=' + wx.getStorageSync('userInfo').orgType,
    })
  },


  //表单提交
  formSubmit: function (e) {
    var formdata = e.detail.value;

    formdata.ageId = this.data.agentItem.id;
    formdata.startTime = this.data.startTime;
    formdata.endTime = this.data.endTime;

    // 开店人
    if (this.data.staffItem.id) {
      formdata.createId = this.data.staffItem.id;
      formdata.createName = this.data.staffItem.realName;
    }
    console.log(this.data.chainItem);
    if (this.data.chainItem && this.data.chainItem.id) {
      formdata.chqId = this.data.chainItem.id
    }

    //详细地址
    formdata.detailAddress = this.data.detailAddress;
    formdata.lng = this.data.longitude;
    formdata.lat = this.data.latitude;

    formdata.coverVideoTime = this.data.coverVideoTime
    formdata.contentVideoTime = this.data.contentVideoTime


    //所在区域
    var address = this.data.address;
    if (address && address.length > 0) {
      formdata.prov = address[0].name
      formdata.proId = address[0].code
      formdata.city = address[1].name
      formdata.cityId = address[1].code
      formdata.disName = address[2].name
      formdata.disId = address[2].code
    }

    formdata.contentVideo = this.data.contentVideo
    formdata.coverVideo = this.data.coverVideo
    // formdata.coverImgs = this.coverImgs.data.datalist
    // formdata.contentImgs = this.contentImgs.data.datalist
    formdata.coverImgs = this.data.coverImgs
    formdata.contentImgs = this.data.contentImgs

    if (this.data.chainItem.id) {
      formdata.chqId = this.data.chainItem.id
    }
    console.log(formdata);

    if (formdata.ageId == '') {
      wx.showToast({
        icon: 'none',
        title: '请选择代理商',
      })
      return
    }

    if (formdata.stoName == '') {
      wx.showToast({
        icon: 'none',
        title: '店铺名不能为空',
      })
      return
    }

    if (formdata.prov == '' || formdata.city == '' || formdata.disName == '') {
      wx.showToast({
        icon: 'none',
        title: '请选择区域',
      })
      return
    }

    if (formdata.detailAddress == '' || formdata.lng == '') {
      wx.showToast({
        icon: 'none',
        title: '请选择详细地址',
      })
      return
    }

    if (formdata.director == '') {
      wx.showToast({
        icon: 'none',
        title: '负责人姓名不能为空',
      })
      return
    }

    if (formdata.mobile == '') {
      wx.showToast({
        icon: 'none',
        title: '手机号码不能为空',
      })
      return
    }


    if (formdata.startTime == '' || formdata.endTime == '') {
      wx.showToast({
        icon: 'none',
        title: '请选择起始或结束时间',
      })
      return
    }

    if (formdata.coverImgs && formdata.coverImgs.length < 1) {
      wx.showToast({
        icon: 'none',
        title: '请上传店铺轮播图片',
      })
      return
    }

    if (formdata.contentImgs && formdata.contentImgs.length < 1) {
      wx.showToast({
        icon: 'none',
        title: '请上传店铺介绍图片',
      })
      return
    }

    this.formRequest(formdata);
  },




  //请求
  formRequest: function (formdata) {
    var url = '/org/protected/bizOrg/createStore';
    var title = "发布成功"
    //修改
    if (this.data.id) {
      url = "/org/protected/bizOrg/updateStore";
      formdata.id = this.data.cententDetail.id;
      title = "修改成功"
    }

    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: formdata
    }, (res) => {
      console.log(res)
      wx.showToast({
        title,
      })
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/publish/store/list',
        })
      }, 1500)

    })
  },

  //获取店铺详情
  getdetail: function () {
    var that = this
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/org/protected/comm/beanCrud/org.StoreVO/getById/' + this.data.id,
      // url: app.globalData.apiUrl + '/org/store/detail?id=' + this.data.id,
      method: 'get'
    }, (res) => {

      if (res && res.vo) {
        console.log(res.vo);
        const userInfo = wx.getStorageSync('userInfo');
        var data = res.vo
        let redTime = moment(data.createDate).add(7, 'd');
        console.log((userInfo.orgType !== 1 || userInfo.orgType !== 4), 111, redTime.isBefore(moment()));
        if (redTime.isBefore(moment()) && userInfo.orgType !== 1 && userInfo.orgType !== 4) {
          this.setData({
            canEdit: true
          })
        }
        that.setData({
          cententDetail: data,
          endTime: data.endTime.substr(0, 5),
          startTime: data.startTime.substr(0, 5),
          address: [{
            name: data.prov,
            code: data.proId
          }, {
            name: data.city,
            code: data.cityId
          }, {
            name: data.disId,
            code: data.disName
          }],
          coverVideo: data.coverVideo,
          contentVideo: data.contentVideo,
          detailAddress: data.detailAddress,
          longitude: data.lng,
          latitude: data.lat,
          agentItem: {
            id: data.ageId,
            ageName: data.ageName || '代理商名',
          },
          staffItem: {
            id: data.createId,
            realName: data.createName || ''
          },
          chainItem: {
            id: data.id,
            chqName: data.chqName || ''
          }
        })
        that.dragcoverImgs.init()
        that.dragcontentImgs.init()

        //不是平台隐藏选择供应商 
        if (wx.getStorageSync('userInfo').orgType == 1) {
          that.setData({
            hideSup: true,
            hideOpen: true
          })
        }
        // 不是平台和供货商管理隐藏开店人
        if (wx.getStorageSync('userInfo').orgType == 2) {
          that.setData({
            hideOpen: true
          })
        }


      }


    })
  },




  // 获取轮播图和介绍图片
  getImg: function () {
    var that = this
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/org/protected/comm/beanCrud/org.StoreImgVO/find',
      method: 'post',
      data: {
        stoId: this.data.id,
        pageSize: 100
      }
    }, (res) => {
      var coverImgs = [],
        contentImgs = []
      var list = res.list;
      list.map((item) => {
        if (item.imgType == 1) {
          coverImgs.push(item)
        } else if (item.imgType == 2) {
          contentImgs.push(item)
        }
      })


      //拖拽coverImgs 
      if (coverImgs.length > 0) {
        coverImgs.map(item => {
          item.fixed = false
        })
      }

      //拖拽coverImgs 
      if (contentImgs.length > 0) {
        contentImgs.map(item => {
          item.fixed = false
        })
      }

      that.setData({
        coverImgs: coverImgs,
        contentImgs: contentImgs,
      })

      that.dragcoverImgs.init()
      that.dragcontentImgs.init()
      // this.coverImgs.setData({
      //   datalist: coverImgs,
      //   originImgs: coverImgs
      // })
      // this.contentImgs.setData({
      //   datalist: contentImgs,
      //   originImgs: contentImgs
      // })
    })
  },

  // 获取代理商列表
  findAgentList: function () {
    var that = this
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + "/org/protected/bizOrg/findAgentList",
      method: "post",
      data: {}
    }, (res) => {
      var list = res.list
      if (list.length >= 1) {
        this.setData({
          agentItem: {
            id: list[0].id,
            ageName: list[0].ageName || '请选择代理商'
          }
        })
      }
    })
  },
















  //**************轮播拖拽**************
  sortEnd(e) {
    this.setData({
      coverImgs: e.detail.listData
    });
  },
  change(e) {
    this.setData({
      coverImgs: e.detail.listData
    });
    this.dragcoverImgs.init()
  },
  sizeChange(e) {
    wx.pageScrollTo({
      scrollTop: 0
    })
    this.setData({
      size: e.detail.value
    });
    this.dragcoverImgs.init();
  },

  itemClick(e) {
    console.log(e);
  },
  toggleFixed(e) {
    let key = e.currentTarget.dataset.key;
    let {
      coverImgs
    } = this.data;
    coverImgs[key].fixed = !coverImgs[key].fixed
    this.setData({
      coverImgs: coverImgs
    });
    this.dragcoverImgs.init();
  },


  add(e) {
    let coverImgs = this.data.coverImgs;
    var that = this
    wx.chooseImage({
      count: that.data.coverImgsnum - that.data.coverImgs.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        that.uploadFile(res.tempFilePaths, 'coverImgs')
      }
    });
  },


  // *********介绍图录播 *********
  contentSortEnd(e) {
    this.setData({
      contentImgs: e.detail.listData
    });
  },
  contentChange(e) {
    this.setData({
      contentImgs: e.detail.listData
    });
    this.dragcontentImgs.init()
  },
  contentSizeChange(e) {
    wx.pageScrollTo({
      scrollTop: 0
    })
    this.setData({
      size: e.detail.value
    });
    this.dragcontentImgs.init();
  },

  contentItemClick(e) {
    console.log(e);
  },
  contentToggleFixed(e) {
    let key = e.currentTarget.dataset.key;
    let {
      contentImgs
    } = this.data;
    contentImgs[key].fixed = !contentImgs[key].fixed
    this.setData({
      contentImgs: contentImgs
    });
    this.dragcontentImgs.init();
  },

  contentAdd(e) {
    let contentImgs = this.data.contentImgs;
    var that = this
    wx.chooseImage({
      count: that.data.contentImgsnum - that.data.coverImgs.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        that.uploadFile(res.tempFilePaths, 'contentImgs')
      }
    });
  },










  //上传图片
  uploadFile: function (pics, idName) {
    var that = this;
    var listData = this.data[idName]
    this.setData({
      loading: true
    })
    for (var i = 0; i < pics.length; i++) {
      (function (i) {
        //   setTimeout(function () { 
        wx.uploadFile({
          url: app.globalData.apiUrl + '/org/protected/comm/file/org.StoreVO/fileUpload',
          header: {
            "Authorization": wx.getStorageSync('Authorization'),
          },
          formData: {
            width: 750
          },
          filePath: pics[i],
          name: 'file',
          success: function (res) {
            if (typeof res.data == "string") {
              var resdata = JSON.parse(res.data)
            }
            if (resdata.success) {

              var item = {
                imgName: resdata.datas.vo.fileName,
                imgPath: resdata.datas.vo.relativeFilePath,
                fixed: false
              }
              listData.push(item)
              that.setData({
                [idName]: listData
              })

              //初始化组件
              if (idName == 'coverImgs') {
                that.dragcoverImgs.init();
              } else if (idName == 'contentImgs') {
                that.dragcontentImgs.init();
              }

              //最后一张关闭遮罩 
              console.log(i + 1 == pics.length, 'last')
              if (i + 1 == pics.length) {
                that.setData({
                  loading: false
                })
              }

            }
          },
          fail: function (res) {
            // wx.showToast({
            //   icon: 'none',
            //   title: '图片上传失败',
            // })
          }
        })
        //   }, (i + 1) * 800);
      })(i)
    }
  },

  scroll(e) {
    this.setData({
      pageMetaScrollTop: e.detail.scrollTop
    })
  },

  // 页面滚动
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },


})